#include "config.h"
#include "utils.h"

#define TAG "cfg"

void Config::set_mqtt_en(uint16_t value)
{
    if(mqtt_en == value) return;
    limit(value, (uint16_t)0, (uint16_t)1);
    ESP_LOGD(TAG,"mqtt_en:%d -> %d\n", mqtt_en, value);
    mqtt_en = value;
    prefs.putUInt(KEY_MQTT_EN, value);
}
uint16_t Config::get_mqtt_en()
{
    return mqtt_en;
}

void Config::set_mqtt_interval(uint16_t value)
{
    if(mqtt_interval == value) return;
    limit(value, (uint16_t)1, (uint16_t)3600);
    ESP_LOGD(TAG,"mqtt_interval:%d -> %d\n", mqtt_interval, value);
    mqtt_interval = value;
    prefs.putUInt(KEY_MQTT_INTERVAL, value);
    return;
}
uint16_t Config::get_mqtt_interval()
{
    return mqtt_interval;
}

void Config::set_mqtt_url(String value)
{
    if(mqtt_url == value) return;
    ESP_LOGD(TAG,"mqtt_url:%s -> %s\n", mqtt_url.c_str(), value.c_str());
    mqtt_url = value;
    prefs.putString(KEY_MQTT_URL, value);
    return;
}

String Config::get_mqtt_url()
{
    return mqtt_url;
}
String Config::get_mqtt_server()
{
    int index = mqtt_url.indexOf(':');
    String server = mqtt_url.substring(0, index);
    ESP_LOGD(TAG,"server:[%s]\n",server.c_str());
    return server;
}
uint16_t Config::get_mqtt_port()
{
    uint16_t port = 1883;
    int index = mqtt_url.indexOf(':');
    if (index != -1)
    {
        String p = mqtt_url.substring(index + 1, mqtt_url.length());
        uint16_t port = p.toInt();
    }
    Serial.print("port:");
    Serial.println(port);
    return port;
}
void Config::set_mqtt_name(String value)
{
    if(mqtt_name == value) return;
    ESP_LOGD(TAG,"mqtt_name:%s -> %s\n", mqtt_name.c_str(), value.c_str());
    mqtt_name = value;
    prefs.putString(KEY_MQTT_NAME, value);
    return;
}
String Config::get_mqtt_name()
{
    return mqtt_name;
}

void Config::set_mqtt_pwd(String value)
{
    if(mqtt_pwd == value) return;
    ESP_LOGD(TAG,"mqtt_pwd:%s -> %s\n", mqtt_pwd.c_str(), value.c_str());
    mqtt_pwd = value;
    prefs.putString(KEY_MQTT_PWD, value);
    return;
}
String Config::get_mqtt_pwd()
{
    return mqtt_pwd;
}

void Config::set_mqtt_cert(String value)
{
    if(mqtt_cert == value) return;
    ESP_LOGD(TAG,"mqtt_cert:%s -> %s\n", mqtt_cert.c_str(), value.c_str());
    mqtt_cert = value;
    prefs.putString(KEY_MQTT_CERT, value);
    return;
}
String Config::get_mqtt_cert()
{
    return mqtt_cert;
}
